﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Sealight.UI.WebUI.Models;
using Sealight.CoreAPI;
using Sealight.API.Ioc;
using System.Web.Routing;
using System.Web.Security;
using System.Text;
using Sealight.Core.DataAdapter;
using Sealight.API.Framework;
using log4net;
using Sealight.UI.WebUI.UIHelpers;
using Sealight.API.Framework.Security;

namespace Sealight.UI.WebUI.Areas.Admin.Controllers.Users
{
    public class UsersController : Controller
    {
        private static readonly ILog log = LogManager.GetLogger(typeof(UsersController));

        public IFormsAuthenticationService FormsService { get; set; }
        public IUserService UserService { get; set; }

        protected override void Initialize(RequestContext requestContext)
        {
            if (FormsService == null) { FormsService = new FormsAuthenticationService(); }
            if (UserService == null) { UserService = IocContainer.Container().Resolve<IUserService>(); }

            base.Initialize(requestContext);
        }

        public ActionResult Login()
        {
            return View("_Login");
        }

        public ActionResult Logout()
        {
            this.FormsService.SignOut();
            return RedirectToAction("login", "users");
        }
        [Sealight.UI.WebUI.UIHelpers.SessionExpireFilter]
        [Authorize]
        public ActionResult Settings()
        {
            user data = null;
            if (SessionWrapper.GetLoginUser() != null)
            {
                data = this.UserService.GetById(SessionWrapper.GetLoginUser().id);
            }
            return View("_Settings", data);
        }
        [Sealight.UI.WebUI.UIHelpers.SessionExpireFilter]
        [Authorize]
        public ActionResult UpdateProfile()
        {
            string email = string.Empty;
            string password = string.Empty;
            string username = string.Empty;

            Guid userId = Guid.Empty;

            if (Request["username"] != null)
            {
                username = Request["username"].ToString();
            }

            if (Request["email"] != null)
            {
                email = Request["email"].ToString();
            }

            if (Request["password"] != null)
            {
                password = Request["password"].ToString();
            }

            if (Request["userId"] != null)
            {
                try
                {
                    userId =new Guid(Request["userId"].ToString());
                }
                catch { }
            }
            AjaxOperationResponse response = new AjaxOperationResponse();
            user data = null;
            try
            {
                if(userId!=Guid.Empty)
                {
                    data = new user
                    {
                        id = userId,
                        user_name = username,
                        email_address = email,
                        password = password,
                        last_login_time = DateTime.Now
                    };

                    this.UserService.AddOrUpdate(data);
                }
            }
            catch (Exception ex)
            {
                log.Error("Error while UpdateProfile data.", ex);
                response.OperationComplete = false;
                response.ErrorCode = "4001";
                response.ErrorFriendlyMessage = string.Format("{0}", UIHelpers.Message.Error);

                return Json(response);
            }

            return Json(data);
        }
        [Sealight.UI.WebUI.UIHelpers.SessionExpireFilter]
        [Authorize]
        public ActionResult GetProfile()
        {
            AjaxOperationResponse response = new AjaxOperationResponse();
            user data = null;
            try
            {
                if (SessionWrapper.GetLoginUser() != null)
                {
                    data = this.UserService.GetById(SessionWrapper.GetLoginUser().id);
                }
            }
            catch (Exception ex)
            {
                log.Error("Error while UpdateProfile data.", ex);
                response.OperationComplete = false;
                response.ErrorCode = "4001";
                response.ErrorFriendlyMessage = string.Format("{0}", UIHelpers.Message.Error);

                return Json(response);
            }

            return Json(data, JsonRequestBehavior.AllowGet);
        }

        public ActionResult AuthenticateUser()
        {
            //do login           
            bool auth = false;
            string jsonResponse = string.Empty;
            //IOperationResponse response = null;

            string userName = string.Empty;
            string password = string.Empty;
            string loginMode = string.Empty;
            bool rememberMe = false;
            if (Request["userName"] != null)
                userName = Request["userName"].ToString();

            if (Request["password"] != null)
                password = Request["password"].ToString();
            if (Request["loginMode"] != null)
                loginMode = Request["loginMode"].ToString();
            if (Request["remember"] != null)
            {
                try
                {
                    rememberMe = bool.Parse(Request["remember"]);
                }
                catch
                {
                    if (Request["remember"].ToString().ToLower() == "on")
                        rememberMe = true;
                    else
                        rememberMe = false;
                }
            }

            if (string.IsNullOrEmpty(userName) || string.IsNullOrEmpty(password))
            {
                throw new Exception("Please enter username and password.");
            }
            else
            {
                if (loginMode.ToLower().Equals("cookie")) password = EncDecUtil.Decrypt(password, "sealight");
               
                auth = this.UserService.Authenticate(userName, password);

            }
            if (auth)
            {
                this.RememberMe(rememberMe, userName, password);
                this.FormsService.SignIn(userName, true);
               
                user m = this.UserService.GetByUsername(userName);
                if (m != null)
                {
                    //user has successfully login, set session variable                   
                    UIHelpers.SessionWrapper.SetLoginUser(m);
                }

            }
           
            string rt = auth.ToString();
            return Json(rt);


        }

        public ActionResult CheckSession()
        {
            bool auth = true;
            if (!HttpContext.User.Identity.IsAuthenticated)
                auth = false;

            if (UIHelpers.SessionWrapper.GetLoginUser() == null)
            {
                auth = false;

                this.FormsService.SignOut();
            }

            return Json(auth.ToString());

        }       

        private string GetRandomPassword()
        {
            StringBuilder randomText = new StringBuilder();
            string alphabets = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890@#$&%";
            Random r = new Random();

            for (int j = 0; j < 6; )
            {
                string newPass = alphabets[r.Next(alphabets.Length)].ToString();

                if (randomText.ToString().IndexOf(newPass) == -1)
                {
                    randomText.Append(newPass);

                    j++;
                }

            }

            return randomText.ToString();
        }

        protected void RememberMe(bool remMe, string username, string pwd)
        {
            if (remMe)
            {
                pwd = EncDecUtil.Encrypt(pwd, "sealight");

                HttpCookie myCookie = new HttpCookie("mySealightCookie");
                Response.Cookies.Remove("mySealightCookie");
                Response.Cookies.Add(myCookie);
                myCookie.Values.Add("username", username);
                myCookie.Values.Add("password", pwd);  
                DateTime dtExpiry = DateTime.Now.AddDays(15);
                System.Web.HttpContext.Current.Response.Cookies["mySealightCookie"].Expires = dtExpiry;
            }
            else
            {
                System.Web.HttpContext.Current.Response.Cookies["mySealightCookie"].Expires = DateTime.Now.AddDays(-16);
            }
        }
    }
}
